package net.entelijan.cobean.text.converter;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

import net.entelijan.cobean.text.ITextConverter;
import net.entelijan.cobean.text.IllegalTextException;

public class XMLGregorianCalendarTextConverter implements
		ITextConverter<XMLGregorianCalendar> {

	private SimpleDateFormat dateConverter;

	private transient String pattern = "yyyy-MM-dd";

	public XMLGregorianCalendarTextConverter() {
		super();
		dateConverter = new SimpleDateFormat(pattern);
		dateConverter.setLenient(false);
	}

	public XMLGregorianCalendarTextConverter(String pattern) {
		super();
		dateConverter = new SimpleDateFormat(pattern);
		dateConverter.setLenient(false);
		this.pattern = pattern;
	}

	@Override
	public XMLGregorianCalendar convertToObject(String stringValue)
			throws IllegalTextException {
		try {
			if (stringValue == null || "".equals(stringValue)) {
				return null;
			}
			Date date = new SimpleDateFormat(this.pattern).parse(stringValue);
			Calendar c = Calendar.getInstance();
			c.setTime(date);
			int y = c.get(Calendar.YEAR);
			int m = c.get(Calendar.MONTH);
			int d = c.get(Calendar.DAY_OF_MONTH);
			return DatatypeFactory.newInstance().newXMLGregorianCalendar(
					new GregorianCalendar(y, m, d));
		} catch (Exception e) {
			throw new IllegalTextException("Could not parse '" + stringValue
					+ "'. " + e.getMessage(), e);
		}
	}

	@Override
	public String convertToString(XMLGregorianCalendar gcal) {
		if (gcal == null){
			return null;
		}
		int y = gcal.getYear();
		int m = gcal.getMonth() - 1;
		int d = gcal.getDay();
		GregorianCalendar gcal1 = new GregorianCalendar(y, m, d);
		Date time = gcal1.getTime();
		return new SimpleDateFormat(pattern).format(time);
	}

}
